package com.tbit.uqbike.service.business.brand.config;

import com.tbit.uqbike.constant.BrandRemoteConfigConstant;
import com.tbit.uqbike.manager.exception.BaseException;
import com.tbit.uqbike.object.pojo.BrandRemoteConfig;
import com.tbit.uqbike.webmanager.dao.core.SubAccountDao;
import com.tbit.uqbike.webmanager.util.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;

/**
 * 分佣账号配置校验
 *
 *
 * @author <a href="mailto:chen.chaoxiong@tbit.com.cn">ChenChaoXiong</a>
 * @since 2024/5/9
 */
@Component
public class CommissionValidator extends AbstractConfigValidator{

    @Resource
    private SubAccountDao subAccountDao;

    private static String PARAM_SPLIT = ";";

    private static String KV_SPLIT = "=";

    private static String ACCOUNT = "account";

    @Override
    protected boolean support(BrandRemoteConfig brandRemoteConfig) {
        return BrandRemoteConfigConstant.ADAPAY_CASH_FUWU_FEE.equals(brandRemoteConfig.getConfigType());
    }

    @Override
    public void doValid(BrandRemoteConfig brandRemoteConfig) {
        String paramKV = brandRemoteConfig.getParamKV();
        if (StringUtils.isBlank(paramKV)) {
            throw new IllegalArgumentException("分账配置不能为空");
        }
        String feeAccountNo = fetchFeeAccountNo(paramKV);
        Integer count = subAccountDao.selectUserDivideCountByUserNo(feeAccountNo);
        if (count != null && count > 0) {
            throw new BaseException("该账户已分配比例，不能设为服务费账号");
        }
    }


    /**
     * 获取分账账号
     * @param paramKV 分账服务费账号 参数类型为account=TBIT;fee=3(代表分账账号为TBIT,服务费比例为3%)
     * @return
     */
    private String fetchFeeAccountNo(String paramKV) {
        String[] split = paramKV.split(PARAM_SPLIT);
        return Arrays.stream(split).filter(s -> s.startsWith(ACCOUNT))
                .findFirst()
                .map(s -> s.split(KV_SPLIT))
                .filter(strings -> strings.length > 1 && StringUtils.isNotBlank(strings[1]))
                .map(strings -> strings[1])
                .orElseThrow(() -> new IllegalArgumentException("分账账号不能为空"));
    }
}
